<template>
    <div class="logFund">
         <el-dialog 
            :title=dialog.title
            :visible.sync="dialog.show"
            :close-on-click-modal='false'
            :close-on-press-escape='false'
            :modal-append-to-body="false">
            <div class="form">
                <el-form 
                    ref="form" 
                    :model="form"
                    :rules="form_rules"
                    label-width="120px" 
                    style="margin:10px;width:auto;">
  
                    <el-form-item prop='number'  label="学号:">
                        <span>{{form.number}}</span>
                        <!-- <el-input type="number"  v-model="form.number"></el-input> -->
                    </el-form-item>

                    <el-form-item prop='item'  label="事项:">
                        <el-input type="item" v-model="form.item"></el-input>
                    </el-form-item>

                    <el-form-item label="分数:" >
                        <el-select v-model="form.grade" placeholder="分数">
                            <el-option
                             v-for="(formgrade, index) in format_grade_list"
                             :key="index" 
                             :label="formgrade" :value="formgrade"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    
                    <el-form-item prop='prove'  label="证明:">
                    <el-upload
                      ref="upload"
                      action="/api/profiles/upload"
                      :headers="headers"                      
                      :on-success="handleSuccess"
                      :multiple="false"
                      list-type="picture-card"
                      :auto-upload="true"
                      :before-upload="beforeUpload"
                      :on-remove="handleRemove"
                      :on-preview="handlePictureCardPreview"
                      :on-download="handleDownload"
                      :file-list="fileList"
                      :disable="flag"
                      >                      
                        <i slot="default" class="el-icon-plus"></i>                       

                        <div slot="file" slot-scope="{file}" >
                          <img
                            class="el-upload-list__item-thumbnail"
                            :src="file.url" alt="">

                          <span class="el-upload-list__item-actions">
                            <span
                              class="el-upload-list__item-preview"
                              @click="handlePictureCardPreview(file)">
                              <i class="el-icon-zoom-in"></i>
                            </span>
                            <span
                              v-if="!disabled"
                              class="el-upload-list__item-download"
                              @click="handleDownload(file)">
                              <i class="el-icon-download"></i>
                            </span>
                            <span
                              v-if="!disabled"
                              class="el-upload-list__item-delete"
                              @click="handleRemove(file)">
                              <i class="el-icon-delete"></i>
                            </span>
                          </span>
                        </div>
                    </el-upload>
                    </el-form-item>

                    <el-form-item label="模块:" >
                        <el-select v-model="form.module" placeholder="所属模块">
                            <el-option
                             v-for="(formmodule, index) in format_module_list"
                             :key="index" 
                             :label="formmodule" :value="formmodule"
                            ></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="次序:" >
                        <el-select v-model="form.order" placeholder="所在次序">
                            <el-option
                             v-for="(formorder, index) in format_order_list"
                             :key="index" 
                             :label="formorder" :value="formorder"
                            ></el-option>
                        </el-select>
                    </el-form-item>                   

                    <el-form-item  class="text_right">
                        <el-button @click="dialog.show = false">取 消</el-button>
                        <el-button type="primary" @click='onSubmit("form")'>提  交</el-button>
                    </el-form-item>

                </el-form>
            </div>
        </el-dialog>
        <!-- 图片预览 -->
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>

<script>
export default {
  name: "DialogMate",
  props: {
    dialog: Object,
    form: Object
  },
  data() {
    return {
      format_grade_list: ["1","2","4","5","6","7"],
      format_module_list: ["A","B","C","D","E"],
      format_order_list: ["1","2","4","5","6","7","8","9","10"],
      form_rules: {
        //学号不可修改，删除此规则
        // number: [
        //   { required: true, message: "学号不能为空！", trigger: "blur" }
        // ],
        grade: [
          { required: true, message: "分数不能为空！", trigger: "blur" }
        ],
        item: [
          { required: true, message: "事项不能为空！", trigger: "blur" }
        ],
        prove: [
          { required: true, message: "证明不能为空！", trigger: "blur" }
        ],
        module: [
          { required: true, message: "模块不能为空！", trigger: "blur" }
        ],
        order: [{ required: true, message: "次序不能为空！", trigger: "blur" }]
      },

      dialogImageUrl: '',
      dialogVisible: false,
      disabled: true,
      flag: false,
      headers: {
        'Authorization': localStorage.getItem('token')
      },
      fileList: [],
    };
  },
  watch: {    
    'dialog.show': function(newVal, oldVal) {
      //监听dialog.show的变化，如果变化为true并且this.form.prove有值并且fileList没有值，调用test方法，获取图片
      if (newVal && this.form.prove&&(!this.fileList.length)) {
        this.test(this.form.prove);
        // console.log("调用test方法");
      }
      //监听dialog.show的变化，如果变化为false清空fileList
      if (!newVal) {
        this.fileList = [];
      }
    }
  },
  methods: {
    onSubmit(form) {
      //表单数据验证
      this.$refs[form].validate(valid => {
        if (valid) {
          //表单数据验证完成之后，提交数据;
          //根据dialog.option的值，决定是新增还是编辑
          const url =
            this.dialog.option == "addmate" ? "addmate" : `editmate/${this.form.id}`;
          this.$axios.post(`/api/profiles/${url}`, this.form).then(res => {
            // 操作成功
            this.$message({
              message: "保存成功！",
              type: "success"
            });
            this.dialog.show = false;
            //给父组件传递一个事件update，通知父组件更新数据
            this.$emit("update");
          });
        }
      });
    },
    //图片删除
    handleRemove(file) {    
      //flag为false,让添加按钮显示
      this.flag = false;
      //form.prove设置为空
      this.form.prove = '';
      //delete api/profiles/deleteUpload/:fileName        
      this.$axios.delete('/api/profiles/deleteUpload/'+file.response.filename);    
      //清空fileList
      this.fileList = [];      
      console.log('删除图片成功');
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
      console.log("预览");
      // console.log(file);
    },
    //图片下载
    handleDownload(file) {
      console.log(file);
    },
    //图片上传成功
    handleSuccess(res, file, fileList) {
      //修改fileList状态
      this.fileList = fileList;
      //flag为true,让添加按钮不显示
      this.flag = true;
      //显示下载按钮、删除按钮
      this.disabled = false;
      console.log("图片上传成功");
      //打印上传成功后的图片路径
      //console.log("res.url:"+res.url);  
      //将图片名字赋值给form.prove
      this.form.prove = res.filename;
    },
    //图片获取并传递给upload组件
    async test(prove){
      //get api/profiles/getUpload/:fileName,fileName=1752904429438.png
      //获取图片
      const filename_test = prove;
      const response =await this.$axios.get(`/api/profiles/getUpload/${filename_test}`,{responseType: 'blob'});
      const file={
        filename: filename_test,
        url: URL.createObjectURL(response.data),
        status: 200,
        uid: filename_test,
        type: 'image/png',
        size: 1024,
        response: {
          filename: filename_test
        }
      };
      //将图片传给el-upload组件的fileList属性，并触发上传成功的事件
      this.$refs.upload.fileList.push(file);
      this.$refs.upload.uploadFiles.push(file);
      this.$refs.upload.handleSuccess(file, file,file);
      //打印
      console.log("test方法-图片获取成功");      
    },
    //图片上传前的钩子函数，限制一张图片，限制图片大小不超过2M，并且是JPG/PNG图片格式
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      //打印fileList的长度
      //console.log("length:"+this.fileList.length);
      //只允许上传一张图片
      if (this.fileList.length >= 1) {
        this.$message.error('只能上传一张图片!');
        return false;
      }
      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      if (isJPG || isPNG && isLt2M) {
        return true;
      } else {
        return false;
      }
    },
  }
};
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

